package com.itcast.controller;

import com.itcast.domain.Book;
import com.itcast.service.BookService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
return new Result(flag?Code.SAVE_OK:Code.SAVE_ERA,flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean updated = bookService.update(book);
        return new Result(updated?Code.UPDATE_OK:Code.UPDATE_ERA,updated); // Return HTTP 200 OK with the boolean result
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable int id) {
        boolean deleted = bookService.delete(id);
        return new Result(deleted?Code.DELETE_OK:Code.DELETE_ERA,deleted);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable int id) {
        Book book = bookService.getById(id);
        Integer code=book!=null?Code.GET_OK:Code.GET_ERA;
        String msg=book!=null?"":"数据查询失败，请重试";
return new Result(code,book,msg);
    }

    @GetMapping
    public Result getAll() {
        List<Book> list = bookService.getAll();
        Integer code=list!=null?Code.GET_OK:Code.GET_ERA;
        String msg=list!=null?"":"数据查询失败，请重试";
        return new Result(code,list,msg);}
}
